/**
 * Copyright (C), 2015-2018, 北京译泰教育科技有限公司
 * FileName: IocHelper
 * Author:   andy
 * Date:     18/1/28 上午2:38
 * Description: ${DESCRIPTION}
 * History:
 */
package org.smart4j.framework.helper;

import java.lang.reflect.Field;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.smart4j.framework.annotation.Inject;
import org.smart4j.framework.util.ArrayUtil;
import org.smart4j.framework.util.ReflectionUtil;

/**
 * 依赖注入助手类<br>
 *
 * @author andy
 * @version V1.0
 * @date 18/1/28 上午2:38
 */
public final class IocHelper {

    static {
        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
        if (MapUtils.isNotEmpty(beanMap)) {
            for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {
                // 获取bean与bean实例
                Class<?> beanClass = beanEntry.getKey();
                Object beanInstance = beanEntry.getValue();

                // 获取bean的成员变量
                Field[] beanFields = beanClass.getDeclaredFields();
                if (ArrayUtil.isNotEmpty(beanFields)) {
                    // 遍历bean field
                    for (Field beanField : beanFields) {
                        // 判断当前bean field是否带有@Inject注解
                        if (beanField.isAnnotationPresent(Inject.class)){
                            // 获取对应实例
                            Class<?> beanFieldClass = beanField.getType();
                            Object beanFieldInstance = beanMap.get(beanFieldClass);
                            if (beanFieldInstance != null){
                                // 反射初始化带有@Inject注解的bean field值
                                ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
                            }
                        }
                    }
                }
            }
        }
    }

}
